package top.xinsix.est.controller;

import top.xinsix.est.constants.Constants;
import top.xinsix.est.constants.ResultEnum;
import top.xinsix.est.service.SmsLogService;
import top.xinsix.est.tools.EmptyUtils;
import top.xinsix.est.tools.Result;
import top.xinsix.est.tools.ResultUtils;


import top.xinsix.est.tools.redis.RedisKeyUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 短信控制器
 */
@RestController
@RequestMapping("/api/sms")
public class SmsController {
    private final static Logger logger =Logger.getLogger(SmsController.class);
    @Resource
    private SmsLogService smsLogService;
    @PostMapping("/verifyCode")
    public Result verifyCode(String phone,Integer codeType){
        //验证手机号
        if (!checkPhone(phone)){
            logger.info("手机号码错误phone:"+phone);
            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(),"手机号码错误");
        }
        //验证验证码类型
        if (!checkCodeType(codeType)){
            logger.info("短信类型错误codeType:"+codeType);
            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(),"短信类型错误");
        }
        //验证发送频率
        if (checkSmsCode(phone,codeType)){
            logger.info("验证码发送频率过高");
            return ResultUtils.returnFail("请勿重复发送");
        }
        //发送短信验证
        if (smsLogService.sendMessage(phone,codeType,null)){
            return ResultUtils.returnSuccess();
        }
        return ResultUtils.returnFail();
    }
    //验证发送频率
    public boolean checkSmsCode(String phone,Integer codeType){
        //手机号、短信类型都需要相同
        //est:类型：手机号
        String key=RedisKeyUtils.formatKeyWithPrefix(Constants.Redis.PREFIX_SMS,codeType.toString(),phone);
        if (EmptyUtils.isEmpty(key)){//为空
            return true;
        }else {//不为空
            return false;
        }

    }

    //验证手机号是否正确
    public boolean checkPhone(String phone) {
        if (EmptyUtils.isEmpty(phone)){
            return false;
        }
        return true;
    }
    //验证验证码类型是否正确
    public boolean checkCodeType(Integer codeType){
        if (EmptyUtils.isNotEmpty(codeType)){//不为空
            if (codeType==Constants.Sms.TYPE_REGIST_OR_LOGIN
                    || codeType==Constants.Sms.TYPE_UP_PASS
                    || codeType==Constants.Sms.TYPE_NOTICE){
                return true;
            }
        }
        return false;
    }
}
